//package com.cqgcxy.servlet;
//
//import com.cqgcxy.servlet.dao.UserDao;
//import util.JDBCUtil;
//
//import javax.servlet.ServletContext;
//import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.sql.*;
//import java.util.List;
//import java.util.Map;
//import javax.servlet.http.HttpSession;
//
//@WebServlet(urlPatterns = "/login.do")
//public class LoginServlet extends HttpServlet {
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
//    }
//
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //    System.out.println(request.getCharacterEncoding());
//        req.setCharacterEncoding("UTF-8");//将请求中的字符集保持跟jsp页面一致，才能处理post请求中的中文参数
////    Random rd = new Random();
////    if(rd.nextInt() % 2 == 0){//验证成功，进入系统主页
////    final String USERNAME = "管理员";//模拟数据库中的已知信息
////    final String PASSWORD = "123456";
//        String username = req.getParameter("username");//获取name=username的表单参数
//        String password = req.getParameter("password");
//        System.out.println("username:" + username);
//        System.out.println("password:" + password);
//        //用注册信息来登录
//        ServletContext application = req.getServletContext();//通过已知对象，获取其他对象
//        List<Map<String, Object>> userList = (List)application.getAttribute("userList");
//        boolean flag = false;//是否登录成功
//        for (Map<String, Object> _user : userList) {
//            if (_user.get("username").equals(username) && _user.get("password").equals(password)) {
//
//                UserDao userDao = new UserDao();
//                List user = userDao.queryAllUser(new User());
//                if (user != null) {
//                    //TODO 补全session对象的获取
//                    HttpSession session = req.getSession();
//                    session.setAttribute("username", username);
//                    session.setAttribute("user", user);
////            flag = true;//登录成功，改变状态
//                    resp.sendRedirect(req.getContextPath() + "/user_list.jsp");//绝对路径，不容易出错
//                } else {
//                    if (!flag) {
//                        resp.sendRedirect(req.getContextPath() + "/login_fail.jsp");
//                    }
//                }
//
////    private boolean loginUtil(String username, String password) {
////        // 创建 JDBCUtil 实例
////        JDBCUtil jdbcUtil = new JDBCUtil();
////
////        try {
////            // 获取数据库连接
////            Connection conn = jdbcUtil.getConnection();
////            if (conn != null) {
////                // 构造 SQL 查询语句
////                String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
////
////                // 执行查询
////                ResultSet rs = jdbcUtil.query(sql, username, password);
////
////                // 检查是否有匹配的用户
////                if (rs != null && rs.next()) {
////                    // 用户名和密码匹配，登录成功
////                    return true;
////                }
////            }
////        } catch (SQLException e) {
////            e.printStackTrace();
////        } finally {
////            // 关闭数据库连接
////            jdbcUtil.closeConnection();
////        }
////
////        // 登录失败
////        return false;
////    }
////
////
////
//                private boolean login (String username, String password){
//
//                    //第一步：注册数据库驱动程序
//                    try {
//                        Class.forName("com.mysql.cj.jdbc.Driver");
//                        System.out.println("驱动注册成功，可以进行数据库编程了！");
//                    } catch (ClassNotFoundException e) {
//                        System.out.println("驱动注册失败，请检查classpath或者类名拼写！");
//                        e.getException();
//                        return false;
//                    }
//                    try {
//                        //第二步：连接数据库（本机）
////          Connection user = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb", "root", "123456");
//
//
//                        Connection user = DriverManager.getConnection("jdbc:mysql://10.254.1.38:3306/homework", "developer", "Javaweb@0102");
//                        System.out.println("数据库连接成功，可以执行sql语句了！");
//
//                        //第三步：获得执行预编译sql容器
//                        PreparedStatement pstmt = user.prepareStatement("select * from 01_25_lr where username = ? and password = ?");
//                        //3.1 给sql语句传参
//                        pstmt.setObject(1, username);
//                        pstmt.setObject(2, password);
//                        //第四步：执行查询操作
//                        ResultSet rs = pstmt.executeQuery();
//                        //第三步：创建执行sql语句的窗口对象
////                Statement stmt = user.createStatement();
////
////                //第四步：构造字符串形式的sql语句，并执行
////                String sql = "select * from user where username ='" + username + "'and password = '" + password +"'";
////                ResultSet rs = stmt.executeQuery(sql);
//
//                        //第五步：处理结果
//                        if (rs.next()) {
//                            System.out.println("有数据，表示用户名和密码正确");
//                            user.close();
//                            return true;
//                        } else {
//                            System.out.println("没数据，表示用户名或密码错误");
//                            user.close();
//                            return false;
//                        }
//                    } catch (SQLException e) {
//                        System.out.println("数据库连接失败，请检查控制台的异常提示找出原因！");
//                        e.printStackTrace();
//                        return false;
//                    }
//                }
//            }

package com.qf.lja.servlet;


import com.qf.lja.dao.ProductDao;
import com.qf.lja.dao.TypeDao;
import com.qf.lja.dao.UserDao;
import com.qf.lja.enity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//将请求中的字符集保持跟jsp页面一致，才能处理post请求中的中文参数
        //用户登录
        String username = req.getParameter("username");//获取name=username的表单参数
        String password = req.getParameter("password");
        System.out.println("username:" + username);
        System.out.println("password:" + password);

        //用户登录
        User loginUser = new User(username, password);
//        System.out.println(loginUser);
        UserDao userDao = new UserDao();
        User user = userDao.findByUsernameAndpasswd(username, password);

        if (user == null) {
            System.out.println("用户名或密码错误");
            resp.sendRedirect("loginfail.jsp");
            return;
        }

        //type
        TypeDao typeDao = new TypeDao();
        //productlist
        ProductDao productDao = new ProductDao();


        //用户登录
        HttpSession session = req.getSession();
        session.setAttribute("loginUser", loginUser);
        session.setAttribute("username", username);
        session.setAttribute("user", user);

        //type
        session.setAttribute("typeList", typeDao.getTypeList());

        //productlist
        session.setAttribute("productList", productDao.queryTop10PopularProducts());

        if (user.getUserStatus() == 1) {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");//绝对路径，不容易出错
        } else {
            resp.sendRedirect(req.getContextPath() + "/error/disabled.jsp");//绝对路径，不容易出错
        }
    }
}









